package com.seaside.park.api;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.seaside.common.bean.Result;
import com.seaside.park.bean.CarReception;
import com.seaside.park.bean.ParkLocker;
import com.seaside.park.mapper.CarReceptionMapper;
import com.seaside.park.mapper.ParkLockerMapper;
import com.seaside.park.service.CarReceptionService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Objects;

@Api(tags = "停车柜映射信息管理")
@RestController
@RequestMapping("/api/park-locker")
public class ParkLockerApi {

    @Autowired
    public ParkLockerMapper parkLockerMapper;

    @Autowired
    public CarReceptionService carReceptionService;

    @Autowired
    public CarReceptionMapper carReceptionMapper;

    @Autowired
    public RestTemplate restTemplate;

    @ApiOperation(value = "分页查询停车柜映射信息", response = Result.class)
    @GetMapping("/list")
    public Result<List<ParkLocker>> list(Integer curPage) {
        Page<ParkLocker> page = new Page<>(curPage, 10);
        IPage<ParkLocker> iPage = parkLockerMapper.selectPage(page, new QueryWrapper<>());
        Result<List<ParkLocker>> result = Result.OK("查询成功");
        result.setData(iPage.getRecords());
        return result;
    }

    @ApiOperation(value = "获取停车柜映射信息", response = Result.class)
    @ApiImplicitParam(paramType = "query", name = "id", dataType = "int", required = true, value = "停车柜映射信息ID")
    @GetMapping("/info")
    public Result<ParkLocker> getInfo(@RequestParam Integer id) {
        ParkLocker parkLocker = parkLockerMapper.selectById(id);
        if (parkLocker != null) {
            return Result.OK("查询成功", parkLocker);
        } else {
            return Result.Error("未找到对应的停车柜映射信息");
        }
    }

    @ApiOperation(value = "随机开柜", response = Result.class)
    @PostMapping("/openCabinet")
    public Result<ParkLocker> openCabinet(@RequestParam String cabinetIccid, @RequestParam Integer carReceptionId) {
        // 传递柜子id开启格子
        String url = "http://175.178.225.26:1685/openCabinet?cabinetIccid=" + cabinetIccid;
        try {
            ResponseEntity<Result> response = restTemplate.exchange(
                    url, HttpMethod.POST, HttpEntity.EMPTY, Result.class
            );
            Result result = response.getBody();
            if (result != null && result.isSucess()) {
                // 获取开柜之后的格子id
                String lockId = (String) result.getData();
                // 构造lockerNumber
                String lockerNumber = cabinetIccid + ":" + lockId;
                // 更新接车单中的钥匙信息、车辆信息
                CarReception carReception = carReceptionMapper.selectOne(new QueryWrapper<CarReception>()
                        .eq("id", carReceptionId)
                        .orderByDesc("id")
                        .last("limit 1"));
                if (carReception != null) {
                    carReceptionService.updateCarStatus(carReception.getId(), "已泊位");
                    carReceptionService.updateLockStatus(carReception.getId(), "已入柜");
                }
                // 构造parkLocker存储
                ParkLocker parkLocker = new ParkLocker();
                parkLocker.setLockerNumber(lockerNumber);
                parkLocker.setCarReceptionId(carReceptionId);
                // 避免干扰
                ParkLocker before = parkLockerMapper.selectOne(new QueryWrapper<ParkLocker>()
                        .eq("car_reception_id", carReceptionId));
                if (before == null || before.getId() == 0) {
                    parkLockerMapper.insert(parkLocker);
                } else {
                    before.setLockerNumber(lockerNumber);
                    parkLockerMapper.updateById(before);
                }
                return Result.OK("开柜成功，锁ID已创建！", lockerNumber);
            } else {
                return Result.Error("开柜失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.Error("开柜接口调用失败");
        }
    }

    @ApiOperation(value = "开格", response = Result.class)
    @PostMapping("/openCell")
    public Result<ParkLocker> openCell(@RequestParam String cellId, @RequestParam Integer carReceptionId) {
        // 传递柜子id开启格子
        String url = "http://175.178.225.26:1685/openCell?cellId=" + cellId;
        try {
            ResponseEntity<Result> response = restTemplate.exchange(
                    url, HttpMethod.POST, HttpEntity.EMPTY, Result.class
            );
            Result result = response.getBody();
            if (result != null && result.isSucess()) {
                CarReception carReception = carReceptionMapper.selectOne(new QueryWrapper<CarReception>()
                        .eq("id", carReceptionId));
                if (carReception != null) {
                    carReceptionService.updateLockStatus(carReception.getId(), "已出柜");
                }
                return Result.OK("开柜成功！使用后请及时关闭！");
            } else {
                return Result.Error("开柜失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.Error("开柜接口调用失败");
        }
    }

    @ApiOperation(value = "删除停车柜映射信息", response = Result.class)
    @ApiImplicitParam(paramType = "query", name = "id", dataType = "int", required = true, value = "停车柜映射信息ID")
    @PostMapping("/delete")
    public Result<String> deleteInfo(@RequestParam Integer id) {
        parkLockerMapper.deleteById(id);
        return Result.OK("删除成功！");
    }

    @ApiOperation(value = "上传锁的照片", response = Result.class)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "id", dataType = "int", required = true, value = "订单编号"),
            @ApiImplicitParam(paramType = "query", name = "lock_photo", dataType = "String", required = true, value = "锁的照片，Base64编码")
    })
    @PostMapping("/upload-lock-photo")
    public Result<String> uploadLockPhoto(@RequestParam("lockerNumber") String lockerNumber, @RequestParam("lockerPhoto") String lockerPhoto) {
        try {
            ParkLocker pl = parkLockerMapper.selectOne(new QueryWrapper<ParkLocker>().eq("locker_number", lockerNumber));
            pl.setLockerPhoto(lockerPhoto);
            parkLockerMapper.updateById(pl);
            return Result.OK("锁的照片上传成功");
        } catch (Exception e) {
            return Result.Error("锁的照片上传失败：" + e.getMessage());
        }
    }
}
